//
//  TPHomeViewController.m
//  XTCloud
//
//  Created by QA on 2017/3/3.
//  Copyright © 2017年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "TPHomeViewController.h"
#import "TPHomeViewCell.h"
#import "DateTimeFormat.h"

#import "MJRefresh.h"

#import "CircleProgressView.h"
#import "WebServiceCommonRequest.h"
#import "NSDictionary+DataFormat.h"

#import "UIColorDispose.h"
#import "PMJobOrderDetailViewController.h"
#import "PMJobOrderListViewController.h"

#import "UIView+AssistView.h"

@interface TPHomeViewController ()

@property (nonatomic,strong) IBOutlet UITableView *tableView;
@property (nonatomic,strong) IBOutlet UIView *tableHeaderView;

@property (strong, nonatomic) NSMutableArray *firstResultData;
@property (strong, nonatomic) NSMutableArray *lastResultData;
@property (strong, nonatomic) NSMutableArray *rwdResultData;

@property (nonatomic,strong) IBOutlet UILabel *timeLabel;
@property (nonatomic,strong) IBOutlet UIView *chartView;
@property (nonatomic,strong) IBOutlet UILabel *RWDSLabel;
@property (nonatomic,strong) IBOutlet UILabel *FCCCLabel;
@property (nonatomic,strong) IBOutlet UILabel *JHFLLabel;
@property (nonatomic,strong) IBOutlet UILabel *WCFLLabel;

@property (nonatomic,strong) IBOutlet UILabel *DGDSLabel;
@property (nonatomic,strong) IBOutlet UILabel *GBDSLabel;
@property (nonatomic,strong) CircleProgressView *circleProgress;

@end

@implementation TPHomeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle:@"实时生产看板"];
        [self addStationToNavigationItem];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.firstResultData = [NSMutableArray array];
    self.lastResultData = [NSMutableArray array];
    self.rwdResultData = [NSMutableArray array];
    
    self.tableView.tableHeaderView= self.tableHeaderView;
    self.tableView.tableFooterView= [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 10)];
    [self.tableView registerClass:[TPHomeViewCell class] forCellReuseIdentifier:@"TPHomeViewCell"];
    
    self.circleProgress = [[CircleProgressView alloc] initWithFrame:CGRectMake(0, 0, 145, 145)];
    self.circleProgress.backgroundColor = [UIColor clearColor];
    [self.chartView addSubview:self.circleProgress];
    
    self.circleProgress.percent = 0;
    self.circleProgress.centerLabel.text = [NSString stringWithFormat:@"%.01f%%", 0.0];
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self updateStationNotification:nil];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    [self getNetworkBaseData];
}

- (void)getNetworkBaseData
{
    //站点ID
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    
    //@状态（全部、供毕、正供、待供）
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"SCDD_HOME_LIST"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    [content setStationID:[model.stationId integerValue]];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        [self.tableView removeAllCustomFromSuperview];
        [self.tableView headerEndRefreshing];
        
        //添加数据，刷新页面
        NSArray *firstArray = nil;
        NSArray *lastArray = nil;
        NSArray *rwdArray = nil;
        if(result.resultArray && result.resultArray.count>=3){
            firstArray = [result.resultArray objectAtIndex:0];
            lastArray = [result.resultArray objectAtIndex:1];
            rwdArray = [result.resultArray objectAtIndex:2];
        }
        
        //设置头部页面
        if(firstArray && firstArray.count>0){
            [self.firstResultData removeAllObjects];
            [self.firstResultData addObjectsFromArray:firstArray];
            [self setHeaderViewData:firstArray.firstObject];
        }
        
        if(rwdArray && rwdArray.count>0){
            [self.rwdResultData removeAllObjects];
            [self.rwdResultData addObjectsFromArray:rwdArray];
            [self setHeaderRWDViewData:rwdArray.firstObject];
        }
        
        if(lastArray && lastArray.count>0){
            [self.lastResultData removeAllObjects];
            [self.lastResultData addObjectsFromArray:lastArray];
            [self.tableView reloadData];
        } else {
            [self.tableView showPromptViewText:@"暂无任务单" rect:CGRectMake(0, 0, SuperWidth, SuperHeight + 160) blcok:nil];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self.tableView headerEndRefreshing];
        [self.tableView showPromptViewText:@"哦，出错了" rect:CGRectMake(0, 0, SuperWidth, SuperHeight + 160) blcok:^{
            [self updateStationNotification:nil];
        }];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self.tableView headerEndRefreshing];
        [self.tableView showPromptViewText:@"无法连接网络" rect:CGRectMake(0, 0, SuperWidth, SuperHeight + 160) blcok:^{
            [self updateStationNotification:nil];
        }];
    }];
}

- (void)setHeaderViewData:(NSDictionary*)mDictionary
{
    CGFloat jhfl = [mDictionary objectFormatFloatForKey:@"计划方量" retain:1 except:0];
    CGFloat yfhl = [mDictionary objectFormatFloatForKey:@"发货方量" retain:1 except:0];
    CGFloat zjfl = [mDictionary objectFormatFloatForKey:@"追加方量" retain:1 except:0];
    CGFloat sjfl = jhfl + zjfl;//实际计划方量
    
    CGFloat wfhfl = (sjfl-yfhl) <=0 ? 0 : sjfl-yfhl; //未发货方量
    CGFloat ccfl = (sjfl-yfhl) <0 ? fabs(sjfl - yfhl) : 0; //超出方量
    
    self.RWDSLabel.text = [mDictionary objectFormatStringForKey:@"任务单数量" format:@"%@" defaults:@"0"];
    self.FCCCLabel.text = [mDictionary objectFormatStringForKey:@"车次" format:@"%@" defaults:@"0"];
    self.JHFLLabel.text = [NSString stringWithFormat:@"%0.1fm³", sjfl];
    self.WCFLLabel.text = [mDictionary objectFormatStringForKey:@"发货方量" format:@"%@m³" defaults:@"0"];
    
    if(ccfl>0){
        CGFloat mProgress = ccfl/sjfl;
        self.circleProgress.percent = mProgress;
        self.circleProgress.centerLabel.text = [NSString stringWithFormat:@"%.01f%%", mProgress*100];
        
        self.circleProgress.topLabel.text = @"超出计划量";
        self.circleProgress.bottomLabel.text = [NSString stringWithFormat:@"超%0.1fm³",ccfl];
        self.circleProgress.progressColor = [UIColorDispose colorWithHexString:@"#EF5350"];
        self.circleProgress.progressBackgroundColor = [UIColorDispose colorWithHexString:@"#6DCAEC"];
    } else {
        CGFloat mProgress = yfhl/sjfl;
        self.circleProgress.percent = mProgress;
        self.circleProgress.centerLabel.text = [NSString stringWithFormat:@"%.01f%%", mProgress*100];
        
        self.circleProgress.topLabel.text = @"已完成占比";
        self.circleProgress.bottomLabel.text = [NSString stringWithFormat:@"剩%0.1fm³",wfhfl];
        self.circleProgress.progressColor = [UIColorDispose colorWithHexString:@"#6DCAEC"];
        self.circleProgress.progressBackgroundColor = [UIColorDispose colorWithHexString:@"#E6E6E6"];
    }
    
    NSString *nowTime = [DateTimeFormat getNowDateFormatter:@"yyyy-MM-dd HH:mm:ss"];
    NSString *showString = [NSString stringWithFormat:@"以下为%@数据",nowTime];
    self.timeLabel.text = showString;
}

- (void)setHeaderRWDViewData:(NSDictionary*)rwdDictionary
{
    self.DGDSLabel.text = [rwdDictionary objectFormatStringForKey:@"待供单数" format:@"当前待供%@单" defaults:@"当前待供0单"];
    self.GBDSLabel.text = [rwdDictionary objectFormatStringForKey:@"供毕单数" format:@"当前供毕%@单" defaults:@"当前供毕0单"];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma make - Station Notification

-(void)updateStationNotification:(StationInfoEntity*)model
{
    [self.lastResultData removeAllObjects];
    [self.tableView reloadData];
    
    //显示进度条
    [self.tableView showViewProgressRect:CGRectMake(0, 0, SuperWidth, SuperHeight + 160)];
    [self getNetworkBaseData];
}

#pragma mark - Table view data source

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.lastResultData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TPHomeViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TPHomeViewCell"];
    
    NSDictionary *dictionary = [self.lastResultData objectAtIndex:indexPath.section];
    cell.RWDCodeLabel.text = [dictionary objectFormatStringForKey:@"任务单编号" defaults:@"未知"];
    cell.GCMCLabel.text = [dictionary objectFormatStringForKey:@"工程名称" defaults:@"未知"];
    //cell.SGDWLabel.text = [dictionary objectFormatStringForKey:@"施工单位" defaults:@"未知"];
    cell.SGBWLabel.text = [dictionary objectFormatStringForKey:@"施工部位" defaults:@"未知"];
    cell.GDDZLabel.text = [dictionary objectFormatStringForKey:@"工地地址" defaults:@"未知"];
    cell.StateLabel.text = [dictionary objectFormatStringForKey:@"状态" defaults:@"未知"];
    cell.CCLabel.text = [dictionary objectFormatStringForKey:@"数量" defaults:@"未知"];
    cell.QDDJLabel.text = [dictionary objectFormatStringForKey:@"砼强度" defaults:@"未知"];
    cell.JZFSLabel.text = [dictionary objectFormatStringForKey:@"浇筑方式" defaults:@"未知"];
    
    return cell;
}

#pragma mark UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if(section == 0){
        static NSString *identifierBar = @"TPHomeViewCell001";
        TPHomeViewCell *cell = [[TPHomeViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierBar index:1];
        return cell;
    }
    return [[UIView alloc] init];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if(section == 0) return 30;
    else return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 108;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    NSDictionary *dictionary = [self.lastResultData objectAtIndex:indexPath.section];
    
    PMJobOrderDetailViewController *viewController = [[PMJobOrderDetailViewController alloc] initWithValue:dictionary];
    [viewController setStationName:model.stationName StationID:[model.stationId integerValue]];
    [self.navigationController pushViewController:viewController animated:YES];
}

#pragma make - Button Event

- (IBAction)DGSelector:(id)sender
{
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    
    //任务单状态：0全部，1正供，2待供，3供毕
    PMJobOrderListViewController *viewController = [[PMJobOrderListViewController alloc] initWithQueryStyle:2];
    [viewController setStationName:model.stationName StationID:[model.stationId integerValue]];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (IBAction)GBSelector:(id)sender
{
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    
    //任务单状态：0全部，1正供，2待供，3供毕
    PMJobOrderListViewController *viewController = [[PMJobOrderListViewController alloc] initWithQueryStyle:3];
    [viewController setStationName:model.stationName StationID:[model.stationId integerValue]];
    [self.navigationController pushViewController:viewController animated:YES];
}

@end
